const express        = require('express');
const router = express.Router();
var request = require('request');

var xlsxj = require("xlsx-to-json");
var multer  = require('multer')
var cors = require('cors');

const fse = require('fs-extra') 
const crypto = require('crypto');    

router.use(cors())

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '/home/wwwroot/www.talenmall.com/mail/backend/uploads/util/pdf/')
    },
    // filename: function (req, file, cb) {
    //     cb(null, file.originalname)
    // }
})
var upload = multer({ storage: storage });

router.post('/api/uploadXP/:type', upload.fields([{name: 'xlsx'}, {name: 'pdf'}]), 
                fileCheck, (req, res, next) => {
    //originalname
    //filename
    //path
    console.log('hi');
    req.xlsx2json = JSON.parse(req.body.xlsx);
    var successObj = {code: 0, message: "上传成功", xlsxResult: req.xlsx2json};

    var accPath, toPath;
    if(req.params.type == 'p2'){
    	toPath = '';
    }else{
	    accPath = '/home/wwwroot/www.talenmall.com/public/upload/mailAcc'
    	toPath = `${accPath}/${req.params.type}/${ genHashTime(req.files.pdf[0].originalname) }`;

	    try{
	        for(var i=0; i<req.files.pdf.length; i++){

	            var oriFilePath = `${req.files.pdf[i].path}`;
	            fse.copySync(oriFilePath, `${toPath}/${req.files.pdf[i].originalname}`);
	        }

	    }catch(e){
	        res.send({code: 500, message: "server err while copying files", e: e})
	    }
    }

    reqAPI(req.params.type, req.xlsx2json, toPath)
        .then(resp=>{
            res.send({resp: resp, code:0, xlsxResult: req.xlsx2json})
        }, (err)=>{
            res.send({code: 500, message: "文件已上传，邮件发送接口请求错误", err: err})
        })


})

function fileCheck(req, res, next){
	if(req.params.type == 'p2'){
		next();
	}else{
		if(req.files.pdf !== null || req.files.pdf !== undefined){
			if(req.files.pdf.length === 0)
	        	res.send({code: 1, message: 'upload at least one file!'});
		    else{
		        next();
		    }
		}else{
            res.send({code: 1, message: 'upload at least one file!'});
        }
	}
}

function genHashTime(str){
    var ts = new Date().getTime();
    var hash =  crypto.createHmac('sha256', str)
                    .digest('hex').substring(0,16);
    return hash + '_' + ts;
}

function reqAPI(type, rawData, dir){
    var url = `http://www.talenmall.com/api/mail/${type}`;
    var ripeData = ( JSON.stringify(rawData) );
    var ripeDir = (dir);
    var toSend = `data=${ripeData}&dir=${ripeDir}`;

    var p = new Promise((resolve, reject)=>{
        request.post({url:url, form: {data: ripeData, dir: ripeDir}}, 
                function(err,httpResponse,body){
                        /* ... */ 
            
            if(err){
                console.log('request error');
                reject(err);
            }else{
                try{
                    var bodyObj = JSON.parse(body);
                    resolve({body: bodyObj, sent:{data: ripeData, dir: ripeDir} });
                }catch(e){
                	console.log('parse error')
                    reject(body);
                }
                console.log('dir: ' + ripeDir);
            }
                    
        })
    });
    return p;
    
}

module.exports = router;